package com.example.xncs;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import android.net.Uri;

import java.io.File;
import java.util.List;

public class ImagePreviewAdapter extends RecyclerView.Adapter<ImagePreviewAdapter.ViewHolder> {

    private Context context;
    private List<MainActivity.ImageItem> imageList;

    public ImagePreviewAdapter(Context context, List<MainActivity.ImageItem> imageList) {
        this.context = context;
        this.imageList = imageList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image_preview, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MainActivity.ImageItem imageItem = imageList.get(position);

        // 优先使用base64数据加载图片
        if (imageItem.getBase64Data() != null && !imageItem.getBase64Data().isEmpty()) {
            try {
                // 将base64字符串转换为字节数组
                byte[] imageBytes = Base64.decode(imageItem.getBase64Data(), Base64.DEFAULT);
                
                // 使用BitmapFactory从字节数组创建Bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
                
                // 计算合适的缩放比例
                int scale = 1;
                int maxSize = 200; // 预览图不需要太大
                if (options.outWidth > maxSize || options.outHeight > maxSize) {
                    scale = Math.min(options.outWidth / maxSize, options.outHeight / maxSize);
                    if (scale < 1) scale = 1;
                }
                
                // 实际解码图片
                options.inJustDecodeBounds = false;
                options.inSampleSize = scale;
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
                
                if (bitmap != null) {
                    holder.ivPreview.setImageBitmap(bitmap);
                } else {
                    // 如果base64解码失败，使用默认图片
                    holder.ivPreview.setImageResource(android.R.drawable.ic_menu_report_image);
                }
            } catch (Exception e) {
                // 如果base64处理失败，使用默认图片
                holder.ivPreview.setImageResource(android.R.drawable.ic_menu_report_image);
            }
        } else if (imageItem.getImagePath().startsWith("content://")) {
            // 使用ContentProvider URI加载图片
            Uri imageUri = Uri.parse(imageItem.getImagePath());
            Glide.with(context)
                    .load(imageUri)
                    .placeholder(android.R.drawable.ic_menu_gallery)
                    .error(android.R.drawable.ic_menu_report_image)
                    .centerCrop()
                    .into(holder.ivPreview);
        } else {
            // 使用文件路径加载图片
            Glide.with(context)
                    .load(new File(imageItem.getImagePath()))
                    .placeholder(android.R.drawable.ic_menu_gallery)
                    .error(android.R.drawable.ic_menu_report_image)
                    .centerCrop()
                    .into(holder.ivPreview);
        }

        holder.tvImageName.setText(imageItem.getImageName());

        // 点击预览图可以查看大图
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开单张图片浏览
                openImageBrowser(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return imageList.size();
    }

    public void setImageList(List<MainActivity.ImageItem> imageList) {
        this.imageList = imageList;
        notifyDataSetChanged();
    }

    private void openImageBrowser(int position) {
        // 打开图片浏览器，从当前图片开始
        /*
        Intent intent = new Intent(context, AutoPlayActivity.class);
        intent.putExtra("MODE", "BROWSE");
        intent.putExtra("START_POSITION", position);
        intent.putStringArrayListExtra("IMAGE_PATHS", getImagePaths());
        context.startActivity(intent);
        */
    }

    private java.util.ArrayList<String> getImagePaths() {
        java.util.ArrayList<String> paths = new java.util.ArrayList<>();
        for (MainActivity.ImageItem item : imageList) {
            paths.add(item.getImagePath());
        }
        return paths;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPreview;
        TextView tvImageName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPreview = itemView.findViewById(R.id.ivPreview);
            tvImageName = itemView.findViewById(R.id.tvImageName);
        }
    }
}